#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <error.h>
#include <cstdio>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

const std::string comm_path = "./myfifo";

#define DEFAULT -1

#define Creater 2
#define User 3

#define Read O_RDONLY
#define Write O_WRONLY

#define BASE_SIZE 1024

class NamePiped
{
private:
    bool OpenNamePipe(int mode)
    {
        _fd = open(_fifo_path.c_str(),mode);
        if(_fd == DEFAULT)
            return false;
        return true;   
    }

public:
    NamePiped(const std::string& path,int who)
    :_fifo_path(path)
    ,_id(who)
    ,_fd(DEFAULT)
    {
        if(_id == Creater)
        {
            int res = mkfifo(_fifo_path.c_str(),0666);
            if(res != 0)
            {
                perror("mkfifo");
            }
        }

    }

    bool OpenForRead()
    {
        return OpenNamePipe(Read);
    }

    bool OpenForWrite()
    {
        return OpenNamePipe(Write);
    }

    int ReadPipe(std::string* message)
    {
        char buff[BASE_SIZE];
        int n = read(_fd,buff,sizeof(buff));
        if(n != 0)
        {
            *message = buff;
        }
        return n;
    }

    int Writepipe(const std::string& message)
    {
        return write(_fd,message.c_str(),message.size());
    }

    ~NamePiped()
    {
        if(_id == Creater)
        {
            int res = unlink(_fifo_path.c_str());
            if(res != 0)
            {
                perror("unlink");
            }
        }
    }

private:
    const std::string _fifo_path;
    int _fd;
    int _id;
};


